package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient client;
    private RequestParams requestParams;
    private SearchRequest request;

    private PageResult handleResponse(SearchResponse search) {
        SearchHits searchHits = search.getHits();
        long value = searchHits.getTotalHits().value;
        SearchHit[] hits = searchHits.getHits();
        List<HotelDoc> hotels = new ArrayList<>();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            //获取排序值
            Object[] sortValues = hit.getSortValues();
            if(sortValues.length>0)
            {
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            hotels.add(hotelDoc);
        }
        return new PageResult(value,hotels);
    }
    @Override
    public PageResult search(RequestParams requestParams) {
        try {
            SearchRequest request = new SearchRequest("hotel");
            //query
            //构建booleanquery
            buildBasicQuery(requestParams,request);
            //分页
            int page = requestParams.getPage();
            int size = requestParams.getSize();
            request.source().from((page-1)*size).size(size);
            //查询我附近的酒店
            DistanceSearch(requestParams, request);
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            return  handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, List<String>> filters(RequestParams requestParams) {
        //1.准备request
        SearchRequest request = new SearchRequest("hotel");
        //2.准备dsl
        buildBasicQuery(requestParams,request);
        //2.1query信息
        //2.2设置size
        request.source().size(0);
        //2.3聚合
        buildAggregation(request);
        //3.发送请求
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);

            //4.解析结果
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            //4.1根据名称获取平拍结果
            List<String> brandList = getAggreByName(aggregations, "brandAgg");
            //4.4放入map
            result.put("brand", brandList);
            List<String> cityList = getAggreByName(aggregations, "cityAgg");
            //4.4放入map
            result.put("city", cityList);
            List<String> StarList = getAggreByName(aggregations, "starNameAgg");
            //4.4放入map
            result.put("starName", StarList);
            return result;
        }catch (IOException e)
        {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> getSuggestions(String prefix) {
        //1.准备request
        SearchRequest request = new SearchRequest("hotel");
        //2.准备DSL
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "suggestions",
                SuggestBuilders.completionSuggestion("suggestion")
                        .prefix(prefix)
                        .skipDuplicates(true)
                        .size(10)
        ));
        //3.发起请求
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //4.解析结果
        Suggest suggest = response.getSuggest();
        //4.1根据名称获取补全结果
        CompletionSuggestion suggestion = suggest.getSuggestion("suggestions");
        List<CompletionSuggestion.Entry.Option> options1 = suggestion.getOptions();
        List<String> list = new ArrayList<>(options1.size());
        for (CompletionSuggestion.Entry.Option option : options1) {
            String string = option.getText().string();
           list.add(string);
        }
        return list;
    }

    @Override
    public void insertById(Long id) {
        try {
            //1.准备request
            Hotel hotel = getById(id);
            // 2.转换为文档类型
            HotelDoc hotelDoc = new HotelDoc(hotel);
            // 3.将HotelDoc转json
            String json = JSON.toJSONString(hotelDoc);

            // 1.准备Request对象
            IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
            // 2.准备Json文档
            request.source(json, XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("hotel", id.toString());
            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private List<String> getAggreByName(Aggregations aggregations,String AggName)
    {
        //4.1根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(AggName);
        //4.2获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        //4.3遍历
        List<String> brandList = new ArrayList<>();
        HashMap<String, List<String>> result = new HashMap<>();
        for (Terms.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            brandList.add(keyAsString);
        }
        return brandList;
    }
    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders.terms("brandAgg")
                .field("brand")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders.terms("cityAgg")
                .field("city")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders.terms("starNameAgg")
                .field("starName")
                .size(100)
        );
    }

    private void DistanceSearch(RequestParams requestParams, SearchRequest request) {
        String location = requestParams.getLocation();
        if(location!=null&& !location.equals(""))
        {
         request.source().sort(SortBuilders.geoDistanceSort("location",new GeoPoint(location))
                 .order(SortOrder.ASC)
                 .unit(DistanceUnit.KILOMETERS)
         );
        }
    }

    private void buildBasicQuery(RequestParams requestParams,SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String key = requestParams.getKey();
        if(key==null||"".equals(key))
        {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else
        {
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }
        //城市条件
        if(requestParams.getCity()!=null && !requestParams.getCity().equals(""))
        {
            boolQuery.filter(QueryBuilders.termQuery("city", requestParams.getCity()));
        }
        //品牌条件
        if(requestParams.getBrand()!=null&&!requestParams.getBrand().equals(""))
        {
            boolQuery.filter(QueryBuilders.termQuery("brand", requestParams.getBrand()));
        }
        //星级条件
        if(requestParams.getStarName()!=null&&!requestParams.getStarName().equals(""))
        {
            boolQuery.filter(QueryBuilders.termQuery("starName", requestParams.getStarName()));
        }
        //价格条件
        if(requestParams.getMinPrice()!=null&& requestParams.getMaxPrice()!=null)
        {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(requestParams.getMinPrice())
                    .lte(requestParams.getMaxPrice()));
        }

        //2.算分控制
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                //原始查询,相关性算分的查询
                boolQuery,
                //function score的数组
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]
                        {
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD",true),
                                ScoreFunctionBuilders.weightFactorFunction(10))
                        }
        );
        request.source().query(boolQuery);
    }
}
